// 封装分类数据相关的业务代码
import { ref, onMounted } from "vue";
import {onBeforeRouteUpdate} from "vue-router"
import { useRoute } from "vue-router";
import { getCategoryApi } from "@/apis/categoryApi";

export function uesCategory() {
    const categoryData = ref({});
  // 获取当前页面路由信息
  const route = useRoute();
  // 调用接口获取数据
  // id = route.params.id   当调用函数时没有传值时默认是route.params.id
  const getCategoryFn = async (id = route.params.id) => {
    const res = await getCategoryApi(id);
    categoryData.value = res.result;
  };
  // 每次路由变化时都会调用这个钩子函数
  onBeforeRouteUpdate((to) => {
    console.log("路由变化了");
    // to代表要去往新地址的路由参数信息
    getCategoryFn(to.params.id);
  });
  onMounted(() => {
    getCategoryFn();
  });

  return{
    categoryData
  }
}
